package com.sz.controller;

import com.sz.pojo.User;
import com.sz.service.UserSVImpl;
import com.sz.service.VerfySVImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/login")
public class LoginController {
    @Resource
    private VerfySVImpl verfySV;
    @Resource
    private UserSVImpl userSV;

    @RequestMapping("/toLogin")
    public String login(){
        return "login";
    }

    @RequestMapping("/verify")
    public String verify(@RequestParam("username")String username, @RequestParam("password")String password, HttpServletRequest req){
        boolean isPwdTrue = verfySV.isPwdTrue(username, password);
        //session携带用户信息（昵称，权限）
        if (isPwdTrue){
            Map nameAndAuth = verfySV.getNameAndAuth(username);
            if(nameAndAuth!=null){
                HttpSession session = req.getSession();
                session.setAttribute("un",username);
                session.setAttribute("name",nameAndAuth.get("name"));
                session.setAttribute("auth",nameAndAuth.get("authority"));
            }
            //重定向到主页
            return "redirect:/toIndex";
        }else {
            System.out.println("密码错误");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest req){
        HttpSession session = req.getSession();
        session.removeAttribute("un");
        session.removeAttribute("name");
        session.removeAttribute("auth");
        return "forward:/toIndex";
    }

    @RequestMapping("/toHomepage")
    public String toHomepage(HttpServletRequest req, Model model){
        String username =  (String) req.getSession().getAttribute("un");
        int auth = (Integer) req.getSession().getAttribute("auth");
        String authority = "";
        switch (auth){
            case 0: authority = "超级管理员";
                break;
            case 1: authority = "普通管理员";
                break;
            case 2: authority = "普通用户";
                break;
            default:authority = "普通用户";
                break;
        }
        User userinfo = userSV.getUserByUsername(username);
        model.addAttribute("userinfo",userinfo);
        model.addAttribute("authority",authority);
        return "homepage";
    }

    @RequestMapping("/toRegister")
    public String toRegister(){
        return "register";
    }

}
